package func;

import java.util.Optional;
import java.util.Random;
import java.util.function.Supplier;

import org.junit.Test;

/*
public interface Supplier<T> {
    T get();
}
 */
public class SupplierDemo {
	@Test
	public void test1 () {
		// 匿名内部类	
		Supplier<Boolean> s = new Supplier<Boolean>() {
			@Override
			public Boolean get() {
				return new Random().nextBoolean();
			}
		};
		System.out.println(s.get());
	}
	@Test
	public void test2 () {
		// lambda
		Supplier<Boolean> s = () -> new Random().nextBoolean();
		System.out.println(s.get());
	}
	
	private String nextEnglish(int length) {
		StringBuilder sb = new StringBuilder("");
		for (int i = 0 ; i < length ; i++) {
			if (new Random().nextBoolean()) {
				//大写 'A' ~ 'Z'
				sb.append((char)(new Random().nextInt(26) + 65));
			}else {
				//小写 'a' ~ 'z'
				sb.append((char)(new Random().nextInt(26) + 97));
			}
		}
		return sb.toString();
	}
	
	private String nextChinese(int length) {
		StringBuilder sb = new StringBuilder("");
		for (int i = 0 ; i < length ; i++) {
			if (new Random().nextBoolean()) {
				//大写 'A' ~ 'Z'
				sb.append((char)(new Random().nextInt(20902) + 0x4E00));
			}else {
				//小写 'a' ~ 'z'
				sb.append((char)(new Random().nextInt(20902) + 0x4E00));
			}
		}
		return sb.toString();
	}
	
	@Test
	public void test3() {
		// 使用
		String obj = null;
		Optional<String> opt = Optional.ofNullable(obj);
		byte[] bytes= new byte[10];
		new Random().nextBytes(bytes);
		                          // Supplier
		String value = opt.orElseGet(() -> nextEnglish(10));
		System.out.println(value);
	}
}
